package com.csdj.server.controller;

import com.csdj.server.pojo.Admin;
import com.csdj.server.pojo.AdminLoginParam;
import com.csdj.server.pojo.RespBean;
import com.csdj.server.service.IAdminService;
import com.csdj.server.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * @ClassName: LoginController
 * @Author: ZouLi
 * @Description:
 * @Date: 2022/12/13 11:26
 **/
@RestController
@Api(tags = "LoginController登录控制器")
public class LoginController {

    /**
     * 注入adminService
     **/
    @Autowired
    private IAdminService iAdminService;

    /**
     * 注入roleService
     **/
    @Autowired
    private IRoleService roleServiceImpl;

    @PostMapping("/login")
    @ApiOperation(value = "登录之后返回token")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request) {
        return iAdminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword(), adminLoginParam.getCode() ,request);
    }

    @GetMapping("/admin/info")
    @ApiOperation(value = "获取当前用户信息")
    public Admin getCurrUserInfo(Principal principal){
        if(null == principal){
            return null;
        }
        String username = principal.getName();
        Admin user = iAdminService.getUserByUserName(username);
        user.setPassword(null);
        // 根据用户id获取用户角色权限
        user.setRoles(roleServiceImpl.getRolesByUserId(user.getId()));
        return user;
    }

    @PostMapping("/logout")
    @ApiOperation(value = "退出登录")
    public RespBean logout(){
        return RespBean.success("注销成功！");
    }
}
